<?php

namespace App\Orchid\Screens\Post;

use App\Models\Post;
use App\Models\Category;
use App\Models\Tag;
use Illuminate\Http\Request;
use Orchid\Screen\Screen;
use Orchid\Screen\Fields\Input;
use Orchid\Screen\Fields\TextArea;
use Orchid\Screen\Fields\Quill;
use Orchid\Screen\Fields\Select;
use Orchid\Screen\Fields\Upload;
use Orchid\Screen\Fields\Relation;
use Orchid\Screen\Fields\DateTimer;
use Orchid\Support\Facades\Layout;
use Orchid\Screen\Actions\Button;
use Orchid\Support\Facades\Toast;
use Illuminate\Support\Str;

class PostEditScreen extends Screen
{
    /**
     * @var Post
     */
    public $post;

    /**
     * Fetch data to be displayed on the screen.
     *
     * @return array
     */
    public function query(Post $post): iterable
    {
        $this->post = $post;
        
        return [
            'post' => $post,
        ];
    }

    /**
     * The name of the screen displayed in the header.
     */
    public function name(): ?string
    {
        return $this->post->exists ? '编辑文章' : '创建文章';
    }

    /**
     * Display header description.
     */
    public function description(): ?string
    {
        return '创建或编辑博客文章';
    }

    /**
     * The screen's action buttons.
     *
     * @return \Orchid\Screen\Action[]
     */
    public function commandBar(): iterable
    {
        return [
            Button::make('保存文章')
                ->icon('save')
                ->method('save'),
                
            Button::make('删除')
                ->icon('trash')
                ->method('remove')
                ->canSee($this->post->exists),
        ];
    }

    /**
     * The screen's layout elements.
     *
     * @return \Orchid\Screen\Layout[]
     */
    public function layout(): iterable
    {
        return [
            Layout::tabs([
                '主要内容' => Layout::rows([
                    Input::make('post.title')
                        ->title('标题')
                        ->placeholder('文章标题')
                        ->required(),
                        
                    Input::make('post.slug')
                        ->title('Slug')
                        ->placeholder('自定义URL标识，留空将自动生成'),
                        
                    TextArea::make('post.excerpt')
                        ->title('摘要')
                        ->rows(3)
                        ->placeholder('文章摘要，显示在列表页面'),
                        
                    Quill::make('post.content')
                        ->title('内容')
                        ->required(),
                ]),
                
                '设置' => Layout::rows([
                    Select::make('post.status')
                        ->title('状态')
                        ->options([
                            'draft' => '草稿',
                            'published' => '已发布',
                            'archived' => '已归档',
                        ])
                        ->default('draft')
                        ->required(),
                        
                    Relation::make('post.category_id')
                        ->title('分类')
                        ->fromModel(Category::class, 'name'),
                        
                    Relation::make('post.tags')
                        ->title('标签')
                        ->fromModel(Tag::class, 'name')
                        ->multiple(),
                        
                    DateTimer::make('post.published_at')
                        ->title('发布日期')
                        ->enableTime(),
                        
                    Upload::make('post.cover_image_id')
                        ->title('封面图')
                        ->maxFiles(1)
                        ->media(),
                ]),
            ]),
        ];
    }
    
    /**
     * Save post
     *
     * @param Post    $post
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function save(Post $post, Request $request)
    {
        $postData = $request->get('post');
        
        // 如果没有提供slug，则根据标题自动生成
        if (empty($postData['slug'])) {
            $postData['slug'] = Str::slug($postData['title']);
        }
        
        // 确保slug唯一
        if ($post->exists && $post->slug !== $postData['slug']) {
            $postData['slug'] = $this->ensureUniqueSlug($postData['slug'], $post->id);
        } elseif (!$post->exists) {
            $postData['slug'] = $this->ensureUniqueSlug($postData['slug']);
        }
        
        // 设置用户ID
        if (!$post->exists) {
            $postData['user_id'] = auth()->id();
        }
        
        $post->fill($postData)->save();
        
        // 处理标签关联
        if (isset($postData['tags'])) {
            $post->tags()->sync($postData['tags']);
        }
        
        Toast::info($post->exists ? '文章已更新' : '文章已创建');
        
        return redirect()->route('platform.posts');
    }
    
    /**
     * Remove post
     *
     * @param Post $post
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function remove(Post $post)
    {
        $post->delete();
        
        Toast::info('文章已删除');
        
        return redirect()->route('platform.posts');
    }
    
    /**
     * Ensure slug is unique
     *
     * @param string $slug
     * @param int|null $exceptId
     *
     * @return string
     */
    private function ensureUniqueSlug(string $slug, ?int $exceptId = null): string
    {
        $originalSlug = $slug;
        $count = 1;
        
        while (true) {
            $query = Post::where('slug', $slug);
            
            if ($exceptId) {
                $query->where('id', '!=', $exceptId);
            }
            
            $exists = $query->exists();
            
            if (!$exists) {
                break;
            }
            
            $slug = $originalSlug . '-' . $count++;
        }
        
        return $slug;
    }
}